package com.hzit.cart.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.util.PreHashedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
	// 使用本地线程变量存储登录用户名数据，将来只要在一个线程中就可以直接通过: LoginInterceptor.local.get()来取值
	public static ThreadLocal<String> local = new ThreadLocal<>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 1. 获取session
		HttpSession session = request.getSession();
		// 2. 判断session中是否有值
		Object name = session.getAttribute("name");
		Object login = session.getAttribute("login");
		// 3. 如果没有登录就跳转到登录页面
		if(name == null){
			response.sendRedirect("http://thirdparty.hzit.com/login?returnUrl=http://cart.hzit.com");
			return false;
		}
		local.set(login + "");
		return true;
	}

	/**
	 * 本地线程变量用完了，得删除，否则容易出现内存泄露
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		local.remove();
	}
}
